<template>
  <div class="check-history-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Clock /></el-icon>
          <div class="header-text">
            <h2>盘点历史记录</h2>
            <p>查询和分析商品历史盘点数据</p>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 查询条件 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品查询">
          <el-input 
            v-model="searchForm.productKeyword" 
            placeholder="商品编码/名称" 
            clearable 
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="全部仓库" clearable style="width: 150px">
            <el-option label="主仓库" :value="1" />
            <el-option label="分仓A" :value="2" />
            <el-option label="分仓B" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="盈亏状态">
          <el-select v-model="searchForm.diffType" placeholder="全部" clearable style="width: 120px">
            <el-option label="盘盈" value="profit" />
            <el-option label="盘亏" value="loss" />
            <el-option label="账实相符" value="balance" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card shadow="never" class="products-card">
      <div class="section-title">
        <el-icon><Box /></el-icon>
        <span>商品列表</span>
        <el-tag style="margin-left: 12px;">共 {{ products.length }} 个商品有盘点记录</el-tag>
      </div>
      
      <el-table :data="products" stripe border @row-click="handleSelectProduct">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productCode" label="商品编码" width="150">
          <template #default="{ row }">
            <el-link type="primary">{{ row.productCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="200" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="checkCount" label="盘点次数" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.checkCount }}次</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastCheckDate" label="最近盘点" width="180" />
        <el-table-column prop="totalDiffQty" label="累计盈亏" width="120" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffQty)">
              {{ row.totalDiffQty > 0 ? '+' : '' }}{{ row.totalDiffQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="avgAccuracy" label="准确率" width="120" align="center">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.avgAccuracy" 
              :stroke-width="6"
              :status="row.avgAccuracy >= 95 ? 'success' : (row.avgAccuracy >= 85 ? '' : 'exception')"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click.stop="handleViewHistory(row)" size="small">
              <el-icon><View /></el-icon>
              查看历史
            </el-button>
            <el-button link type="success" @click.stop="handleExportHistory(row)" size="small">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 盘点历史详情对话框 -->
    <el-dialog 
      v-model="showHistoryDialog" 
      :title="`${selectedProduct?.productName} 盘点历史`"
      width="90%"
      destroy-on-close
    >
      <div class="history-stats">
        <el-statistic title="盘点总次数" :value="historyRecords.length" suffix="次" />
        <el-statistic title="平均准确率" :value="calculateAvgAccuracy()" suffix="%" />
        <el-statistic title="累计盈亏数量" :value="calculateTotalDiff()" />
        <el-statistic title="累计盈亏金额" :value="calculateTotalAmount()" prefix="¥" />
      </div>

      <!-- 历史记录时间轴 -->
      <el-timeline class="history-timeline">
        <el-timeline-item
          v-for="record in historyRecords"
          :key="record.id"
          :timestamp="record.checkTime"
          placement="top"
          :type="getTimelineType(record)"
        >
          <el-card>
            <div class="record-header">
              <div class="record-info">
                <h4>{{ record.sheetNo }}</h4>
                <el-tag size="small">{{ record.warehouseName }}</el-tag>
                <el-tag size="small" type="info">{{ record.checkPerson }}</el-tag>
              </div>
              <div class="record-status">
                <el-tag :type="getStatusTagType(record.status)">
                  {{ getStatusName(record.status) }}
                </el-tag>
              </div>
            </div>
            
            <el-descriptions :column="4" border size="small" class="record-details">
              <el-descriptions-item label="账面数量">
                <span class="book-qty">{{ record.bookQty }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="实盘数量">
                <span class="actual-qty">{{ record.actualQty }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="盈亏数量">
                <span :class="getDiffClass(record.diffQty)" class="diff-value">
                  {{ record.diffQty > 0 ? '+' : '' }}{{ record.diffQty }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="盈亏金额">
                <span :class="getDiffClass(record.diffAmount)" class="diff-value">
                  {{ record.diffAmount > 0 ? '+' : '' }}¥{{ Math.abs(record.diffAmount).toFixed(2) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="单价" :span="2">
                ¥{{ record.unitPrice.toFixed(2) }}
              </el-descriptions-item>
              <el-descriptions-item label="准确率" :span="2">
                <el-progress 
                  :percentage="record.accuracy" 
                  :stroke-width="6"
                  style="width: 200px;"
                />
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="4">
                <span :class="record.remark ? 'has-remark' : 'no-remark'">
                  {{ record.remark || '无' }}
                </span>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <el-empty v-if="historyRecords.length === 0" description="暂无历史记录" />

      <template #footer>
        <el-button @click="showHistoryDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleCompareRecords">
          <el-icon><DataAnalysis /></el-icon>
          对比分析
        </el-button>
        <el-button type="success" @click="handleExportDetail">
          <el-icon><Download /></el-icon>
          导出详情
        </el-button>
      </template>
    </el-dialog>

    <!-- 趋势图对话框 -->
    <el-dialog v-model="showTrendDialog" title="盘点趋势分析" width="80%" destroy-on-close>
      <div class="trend-chart-container">
        <div class="chart-placeholder">
          <el-icon :size="80" color="#dcdfe6"><TrendCharts /></el-icon>
          <p>盘点数量趋势图</p>
          <p class="chart-desc">显示商品在不同时间的盘点数量变化趋势</p>
          <el-tag type="info">图表组件待集成（ECharts/ChartJS）</el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Clock, Search, Refresh, Box, View, Download, DataAnalysis, TrendCharts
} from '@element-plus/icons-vue'

// 状态
const showHistoryDialog = ref(false)
const showTrendDialog = ref(false)
const selectedProduct = ref(null)

// 搜索表单
const searchForm = reactive({
  productKeyword: '',
  dateRange: [],
  warehouseId: null,
  diffType: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 商品数据
const products = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15 Pro Max 256GB',
    category: '手机',
    checkCount: 8,
    lastCheckDate: '2024-01-15 14:30:00',
    totalDiffQty: -25,
    avgAccuracy: 92
  },
  {
    id: 2,
    productCode: 'P002',
    productName: 'MacBook Pro 14寸 M3',
    category: '笔记本',
    checkCount: 6,
    lastCheckDate: '2024-01-14 16:00:00',
    totalDiffQty: -12,
    avgAccuracy: 94
  },
  {
    id: 3,
    productCode: 'P003',
    productName: 'AirPods Pro 2',
    category: '耳机',
    checkCount: 10,
    lastCheckDate: '2024-01-15 10:00:00',
    totalDiffQty: 15,
    avgAccuracy: 98
  },
  {
    id: 4,
    productCode: 'P004',
    productName: 'iPad Air 5',
    category: '平板',
    checkCount: 5,
    lastCheckDate: '2024-01-13 15:30:00',
    totalDiffQty: -8,
    avgAccuracy: 96
  },
  {
    id: 5,
    productCode: 'P005',
    productName: 'Apple Watch Series 9',
    category: '手表',
    checkCount: 7,
    lastCheckDate: '2024-01-12 11:00:00',
    totalDiffQty: 3,
    avgAccuracy: 97
  }
])

// 历史记录数据
const historyRecords = ref([])

// 方法
const handleSearch = () => {
  pagination.page = 1
  ElMessage.success('查询完成')
}

const handleReset = () => {
  Object.assign(searchForm, {
    productKeyword: '',
    dateRange: [],
    warehouseId: null,
    diffType: ''
  })
  handleSearch()
}

const handleSelectProduct = (row) => {
  selectedProduct.value = row
}

const handleViewHistory = (product) => {
  selectedProduct.value = product
  
  // 模拟加载历史记录
  historyRecords.value = [
    {
      id: 1,
      sheetNo: 'CHS202401150001',
      warehouseName: '主仓库',
      checkPerson: '张三',
      checkTime: '2024-01-15 14:30:00',
      bookQty: 100,
      actualQty: 95,
      diffQty: -5,
      unitPrice: 9999,
      diffAmount: -49995,
      accuracy: 95,
      status: 'approved',
      remark: '发现破损2台，丢失3台'
    },
    {
      id: 2,
      sheetNo: 'CHS202401100002',
      warehouseName: '主仓库',
      checkPerson: '李四',
      checkTime: '2024-01-10 16:00:00',
      bookQty: 105,
      actualQty: 100,
      diffQty: -5,
      unitPrice: 9999,
      diffAmount: -49995,
      accuracy: 95,
      status: 'approved',
      remark: '正常损耗'
    },
    {
      id: 3,
      sheetNo: 'CHS202401050003',
      warehouseName: '主仓库',
      checkPerson: '王五',
      checkTime: '2024-01-05 10:00:00',
      bookQty: 110,
      actualQty: 105,
      diffQty: -5,
      unitPrice: 9999,
      diffAmount: -49995,
      accuracy: 95,
      status: 'approved',
      remark: '账实不符'
    },
    {
      id: 4,
      sheetNo: 'CHS202312280004',
      warehouseName: '主仓库',
      checkPerson: '张三',
      checkTime: '2023-12-28 14:00:00',
      bookQty: 115,
      actualQty: 110,
      diffQty: -5,
      unitPrice: 9999,
      diffAmount: -49995,
      accuracy: 96,
      status: 'approved',
      remark: '展示机损坏'
    },
    {
      id: 5,
      sheetNo: 'CHS202312200005',
      warehouseName: '主仓库',
      checkPerson: '李四',
      checkTime: '2023-12-20 11:30:00',
      bookQty: 120,
      actualQty: 118,
      diffQty: -2,
      unitPrice: 9999,
      diffAmount: -19998,
      accuracy: 98,
      status: 'approved',
      remark: '销售未记录'
    },
    {
      id: 6,
      sheetNo: 'CHS202312150006',
      warehouseName: '主仓库',
      checkPerson: '王五',
      checkTime: '2023-12-15 15:00:00',
      bookQty: 122,
      actualQty: 125,
      diffQty: 3,
      unitPrice: 9999,
      diffAmount: 29997,
      accuracy: 98,
      status: 'approved',
      remark: '发现未入库商品'
    },
    {
      id: 7,
      sheetNo: 'CHS202312100007',
      warehouseName: '主仓库',
      checkPerson: '张三',
      checkTime: '2023-12-10 09:00:00',
      bookQty: 119,
      actualQty: 119,
      diffQty: 0,
      unitPrice: 9999,
      diffAmount: 0,
      accuracy: 100,
      status: 'approved',
      remark: '账实相符'
    },
    {
      id: 8,
      sheetNo: 'CHS202312050008',
      warehouseName: '主仓库',
      checkPerson: '李四',
      checkTime: '2023-12-05 13:30:00',
      bookQty: 119,
      actualQty: 116,
      diffQty: -3,
      unitPrice: 9999,
      diffAmount: -29997,
      accuracy: 97,
      status: 'approved',
      remark: '货损'
    }
  ]
  
  showHistoryDialog.value = true
}

const handleExportHistory = (product) => {
  ElMessage.success(`导出 ${product.productName} 的历史记录`)
}

const handleCompareRecords = () => {
  showHistoryDialog.value = false
  showTrendDialog.value = true
}

const handleExportDetail = () => {
  ElMessage.success('导出详细数据')
}

const calculateAvgAccuracy = () => {
  if (historyRecords.value.length === 0) return 0
  const total = historyRecords.value.reduce((sum, record) => sum + record.accuracy, 0)
  return Math.round(total / historyRecords.value.length)
}

const calculateTotalDiff = () => {
  return historyRecords.value.reduce((sum, record) => sum + record.diffQty, 0)
}

const calculateTotalAmount = () => {
  return historyRecords.value.reduce((sum, record) => sum + record.diffAmount, 0).toFixed(2)
}

const getTimelineType = (record) => {
  if (record.diffQty > 0) return 'success'
  if (record.diffQty < 0) return 'danger'
  return 'primary'
}

const getStatusName = (status) => {
  const map = {
    pending: '待盘点',
    checking: '盘点中',
    completed: '已完成',
    approved: '已审核'
  }
  return map[status] || status
}

const getStatusTagType = (status) => {
  const map = {
    pending: 'info',
    checking: 'warning',
    completed: '',
    approved: 'success'
  }
  return map[status] || ''
}

const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}

// 初始化
pagination.total = products.value.length
</script>

<style scoped>
.check-history-container {
  padding: 20px;
}

.header-card,
.filter-card,
.products-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.profit-text {
  color: #67C23A;
  font-weight: 500;
}

.loss-text {
  color: #F56C6C;
  font-weight: 500;
}

.history-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.history-timeline {
  margin-top: 20px;
  max-height: 500px;
  overflow-y: auto;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.record-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.record-info h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.record-details {
  margin-top: 12px;
}

.book-qty {
  color: #606266;
  font-weight: 500;
}

.actual-qty {
  color: #409EFF;
  font-weight: 500;
}

.diff-value {
  font-weight: 600;
  font-size: 15px;
}

.has-remark {
  color: #303133;
}

.no-remark {
  color: #c0c4cc;
  font-style: italic;
}

.trend-chart-container {
  min-height: 400px;
}

.chart-placeholder {
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 8px;
}

.chart-placeholder p {
  margin: 16px 0 8px 0;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

.chart-desc {
  color: #909399 !important;
  font-size: 14px !important;
  font-weight: 400 !important;
  margin: 0 0 16px 0 !important;
}
</style>

